package de.uni.leipzig.meddins.server;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import de.uni.leipzig.meddins.R;
import de.uni.leipzig.meddins.app.AppSettings;
import de.uni.leipzig.meddins.ui.DroidSocketServerActivity;

public class ServerService extends Service {
	private static final int NOTIFICATION_STARTED_ID = 1;
	private NotificationManager notifyManager = null;
	private SocketServer server = null;

	@Override
	public void onCreate() {
		super.onCreate();
		notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		server = new SocketServer(this);
	}

	@Override
	public void onDestroy() {
		Log.i(ServerService.class.getName(), "Stopping Server Service");
		server.interrupt();
		notifyManager.cancel(NOTIFICATION_STARTED_ID);
		notifyManager = null;
		AppSettings.setServiceStarted(ServerService.this, false);
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		server.start();
		showNotification();
		return START_STICKY;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		return super.onUnbind(intent);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	private void showNotification() {
		Notification notification = new Notification(
				R.drawable.ic_stat_started,
				getString(R.string.service_started), System.currentTimeMillis());

		Intent startIntent = new Intent(this, DroidSocketServerActivity.class);
		startIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

		PendingIntent intent = PendingIntent.getActivity(this, 0, startIntent,
				Intent.FLAG_ACTIVITY_NEW_TASK);

		notification.flags |= Notification.FLAG_ONGOING_EVENT
				| Notification.FLAG_NO_CLEAR;
		notification.setLatestEventInfo(this,
				getString(R.string.notification_started_title),
				getString(R.string.notification_started_text), intent);
		notifyManager.notify(NOTIFICATION_STARTED_ID, notification);
	}
}
